﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IFClientDLL;
using IFServerDLL;
using System.Windows.Forms;
using IFServerDLL.Model;
using System.IO;
using IFServerDLL.DB;
using HCY.CTP.DBShangZheng;
using IFClientDLL.Calc;
using IFClientDLL.MyCalc;

namespace IFClientDemo
{
    public class TryIF_Demo : ITryIF
    {
        private string _serverAddress = "MyClientEndpointVehicleCommand";
        private Guid GetIDByUserName(string username)
        {
            string dir=Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/Tryif";
            string filePath = dir+"/userid.txt";

            if (File.Exists(filePath))
            {
                string[] users = File.ReadAllLines(filePath);
                foreach (var x in users)
                {
                    string[] spl = x.Split(',');
                    if (spl.Length == 2 && spl[0] == username)
                    {
                        return Guid.Parse(spl[1]);
                    }
                }
            }
            Guid id = Guid.NewGuid();
            string value = username + "," + id.ToString()+"\r\n";

            Directory.CreateDirectory(dir);
            File.AppendAllText(filePath, value);
            return id;
        }
        private Form _frm;
        private DBTableMarketDataZi _zi;
        public TryIF_Demo(DBTableMarketDataZi zi, Form frm,string username)
        {
            _zi = zi;
            _frm = frm;
            _id = GetIDByUserName(username);
            _DataServer = new MarketDataManager_DB(this);
            _Client = new ClientBase(this, _serverAddress, "MyClientEndpointVehicleRespone", username, zi.合约);
            _DataServer.OnReceiveDBData += new Action<MyDBData>(_DataServer_OnReceiveData);
            _calc = new MyCalcManager(this);
        }

        void _DataServer_OnReceiveData(MyDBData obj)
        {
            PublishProxy proxy = new PublishProxy(_serverAddress);
            proxy.AddMarketData(_id, obj);

            this.BeginInvoke(() =>
                {
                    if (OnReceiveData != null)
                    {
                        OnReceiveData(obj);
                    }
                });

        }
        
        private IMarketDataServer _DataServer;
        public IMarketDataServer DataServer
        {
            get { return _DataServer; }
        }
        private IClient _Client;
        public IClient Client
        {
            get { return _Client; }
        }

        public void AddUserCommand(UserCommand cmd,Guid calcID)
        {
           
            if (cmd.IsOrderCancel)
            {
                foreach (var x in Client.OrderOnhand)
                {
                    if (x.Instrument == cmd.Instrument)
                    {

                        PublishProxy proxy = new PublishProxy(_serverAddress);
                        proxy.OrderCancel(_id, x.OrdID,  calcID);
                    }
                }
            }
            else
            {
                bool found = false;
                foreach (var x in Client.TradeOnHand)
                {
                    if (x.Instrument == cmd.Instrument)
                    {
                        if (x.BuyOrSell != cmd.BuyOrSell)
                        {
                            found = true;
                            var order= Client.OrderOnhand.Where(p => p.Instrument == cmd.Instrument && p.OpenOrClose ==MyEnumOpenClose.CloseToday && p.BuyOrSell == cmd.BuyOrSell).FirstOrDefault();
                            if (order != null)
                            {
                                PublishProxy proxy = new PublishProxy(_serverAddress);
                                proxy.OrderCancel(_id, order.OrdID,calcID);
                            }
                            PublishProxy proxy2 = new PublishProxy(_serverAddress);
                            proxy2.OrderInsert(_id, new IFServerDLL.Model.UserOrdBase() { BuyOrSell = cmd.BuyOrSell, OpenOrClose = MyEnumOpenClose.CloseToday, Instrument = cmd.Instrument, UserCreateOrdTime = DateTime.Now, Volume =x.SumALLVolume, Price = cmd.Price, CalcID=calcID });
                        }
                    }
                }
                if (found == false)
                {
                    PublishProxy proxy = new PublishProxy(_serverAddress);
                    proxy.OrderInsert(_id, new IFServerDLL.Model.UserOrdBase() { BuyOrSell = cmd.BuyOrSell, OpenOrClose = IFServerDLL.Model.MyEnumOpenClose.Open, Instrument = cmd.Instrument, UserCreateOrdTime = DateTime.Now, Volume = cmd.DftVolume, Price = cmd.Price, CalcID = calcID });
                }

            }


        }

        public void AddMessage(IFServerDLL.Model.MessageBase msg)
        {
            if (OnMessage != null)
            {
                OnMessage(msg);
            }
        }
        private Guid _id;
        public Guid UserID
        {
            get { return _id; }
        }


        public event Action<IFServerDLL.Model.MessageBase> OnMessage;


        public void BeginInvoke(Action action)
        {
            if (_frm.InvokeRequired)
            {
                Action<Action> a = new Action<Action>(BeginInvoke);
                if (_frm != null && _frm.IsDisposed == false&&_frm.Disposing==false)
                {
                    try
                    {
                        _frm.Invoke(a, new object[] { action });
                    }
                    catch
                    {

                    }
                }
            }
            else
            {
                action();
            }
        }


        


        public void AddOrder(UserOrdBase ord)
        {
            PublishProxy proxy = new PublishProxy(_serverAddress);
            proxy.OrderInsert(_id,ord);
        }



        private MyCalcManager _calc;

        public MyCalcManager Calc
        {
            get
            {
               
                return _calc;
            }
           
        }

        

        public event Action<MyDBData> OnReceiveData;

        public void CancelOrder(Guid orderID, Guid calcID)
        {
            PublishProxy proxy = new PublishProxy(_serverAddress);
            proxy.OrderCancel(_id, orderID, calcID);
        }


        public DBTableMarketDataZi DataInfo
        {
            get { return _zi; }
        }
    }
}
